import React, { Component } from 'react'
import axios from 'axios';
import PubSub from 'pubsub-js';


export default class Search extends Component {
  search = async () => {
    // 连续解构赋值+重命名
    const { keyWordElement: { value: keyWord } } = this;
    // this.props.updateAppState({isFirst: false, isLoading: true});
    PubSub.publish('changeWord', { isFirst: false, isLoading: true });
    // https://api.github.com/search/users?q=${keyWord}
    axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
      response => {
        console.log("返回值：", response.data);
        // this.props.updateAppState({ isLoading: false, users: response.data.items });
        PubSub.publish('changeWord', { isLoading: false, users: response.data.items });
      },
      error => {
        // this.props.updateAppState({ isLoading: false, err: error.message });
        PubSub.publish('changeWord', { isLoading: false, err: error.message });
      }
    )

    // fetch 未优化和优化
    fetch("/api2/cars").then(
      response => {
        console.log("返回值：", response);
        return response.json();
      },
      // error => {
      //   console.log("err返回值：", error);
      //   return new Promise(() => {});
      // }
    ).then(
      response => {
        console.log("获取数据成功：", response);
      },
      // error => {
      //   console.log("获取数据失败：", error);
      // }
    ).catch(
      (error) => {
        console.log("获取数据失败：", error);
      }
    )

    // fetch 关注分离：
    try {
      const response = await fetch("/api2/cars");
      const data = await response.json();
      console.log("返回值：", data);
    } catch (error) {
      console.log("err返回值：", error);
    }

  }

  

  render() {
    return (
      <section>
        <h3 className='jumbotron-heading'>搜索github用户</h3>
        <div>
          <input ref={input => this.keyWordElement = input} type="text" placeholder="输入关键字搜索" />
          &nbsp;
          <button onClick={this.search}>搜索</button>
        </div>
      </section>
    )
  }
}
